<!--
  智慧社区管理系统 - 首页仪表盘
  @author Wu.Liang
  @date 2024-01-01
-->
<template>
    <div class="dashboard">
        <!-- 页面头部 -->
        <div class="dashboard-header">
            <h1 class="page-title">智慧社区管理系统</h1>
            <p class="page-description">欢迎使用智慧社区管理系统，为您提供全面的社区管理解决方案</p>
        </div>

        <!-- 统计卡片 -->
        <div class="stats-grid">
            <el-card v-for="stat in statsData" :key="stat.title" class="stat-card" shadow="hover">
                <div class="stat-content">
                    <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                        <el-icon :size="32" color="#fff">
                            <component :is="stat.icon" />
                        </el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-title">{{ stat.title }}</div>
                        <div class="stat-value">{{ stat.value }}</div>
                        <div class="stat-change" :class="stat.trend">
                            <el-icon :size="12">
                                <ArrowUp v-if="stat.trend === 'up'" />
                                <ArrowDown v-if="stat.trend === 'down'" />
                            </el-icon>
                            {{ stat.change }}
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 图表区域 -->
        <div class="charts-grid">
            <el-card class="chart-card" shadow="hover">
                <template #header>
                    <div class="card-header">
                        <span>社区数据概览</span>
                        <el-button text @click="refreshChart">刷新</el-button>
                    </div>
                </template>
                <div class="chart-container" ref="chartRef"></div>
            </el-card>

            <!-- 店铺信息统计缩略图 -->
            <ShopStatsPanel 
                :shop-id="currentShopId"
                :show-refresh="true"
                :show-view-more="true"
                @refresh="handleShopStatsRefresh"
                @view-more="handleShopStatsViewMore"
            />
        </div>

        <!-- 统计卡片 -->
        <div class="stats-grid">
            <el-card v-for="stat in additionalStatsData" :key="stat.title" class="stat-card" shadow="hover">
                <div class="stat-content">
                    <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                        <el-icon :size="32" color="#fff">
                            <component :is="stat.icon" />
                        </el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-title">{{ stat.title }}</div>
                        <div class="stat-value">{{ stat.value }}</div>
                        <div class="stat-change" :class="stat.trend">
                            <el-icon :size="12">
                                <ArrowUp v-if="stat.trend === 'up'" />
                                <ArrowDown v-if="stat.trend === 'down'" />
                            </el-icon>
                            {{ stat.change }}
                        </div>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, markRaw } from 'vue'
import { useRouter } from 'vue-router'
import {
    User,
    House,
    VideoCamera,
    ArrowUp,
    ArrowDown,
    OfficeBuilding,
    Grid,
    HomeFilled,
    UserFilled
} from '@element-plus/icons-vue'
import { formatDate } from '@/utils'
import * as echarts from 'echarts'
import { dashboardApi } from '@/api/dashboard'
import ShopStatsPanel from '@/components/ShopStatsPanel.vue'

// 路由
const router = useRouter()

// 图表引用
const chartRef = ref<HTMLElement>()

// 统计数据
const statsData = ref([
    {
        title: '总用户数',
        value: '0',
        change: '+0%',
        trend: 'up',
        icon: markRaw(User),
        color: '#2d8cf0'
    },
    {
        title: '社区数量',
        value: '0',
        change: '+0%',
        trend: 'up',
        icon: markRaw(House),
        color: '#19be6b'
    },
    {
        title: '停车位',
        value: '1,256',
        change: '-2.1%',
        trend: 'down',
        icon: markRaw(User),
        color: '#ff9900'
    },
    {
        title: '在线设备',
        value: '98.5%',
        change: '+1.3%',
        trend: 'up',
        icon: markRaw(VideoCamera),
        color: '#ed4014'
    }
])

// 公告列表
const noticeList = ref([])

// 当前店铺ID
const currentShopId = ref<number | undefined>(undefined)

// 处理店铺统计刷新
const handleShopStatsRefresh = () => {
    console.log('刷新店铺统计数据')
    // 这里可以添加刷新店铺统计数据的逻辑
    loadDashboardData()
}

// 处理店铺统计查看更多
const handleShopStatsViewMore = () => {
    console.log('查看店铺统计详情')
    // 这里可以添加跳转到店铺统计详情页面的逻辑
    // router.push('/shop/stats')
}

// 额外统计数据
const additionalStatsData = ref([
    {
        title: '总楼栋数',
        value: '0',
        change: '+0%',
        trend: 'up',
        icon: markRaw(OfficeBuilding),
        color: '#722ed1'
    },
    {
        title: '单元统计',
        value: '0',
        change: '+0%',
        trend: 'up',
        icon: markRaw(Grid),
        color: '#13c2c2'
    },
    {
        title: '房户数量',
        value: '0',
        change: '+0%',
        trend: 'up',
        icon: markRaw(HomeFilled),
        color: '#fa8c16'
    },
    {
        title: '业主统计',
        value: '0',
        change: '+0%',
        trend: 'up',
        icon: markRaw(UserFilled),
        color: '#eb2f96'
    }
])

// 刷新图表
const refreshChart = () => {
    loadDashboardData()
}

// 加载仪表盘数据
const loadDashboardData = async () => {
    try {
        const response = await dashboardApi.getDashboardData()
        if (response.code === 200 && response.data) {
            const data = response.data
            
            // 更新统计数据
            if (data.stats) {
                statsData.value[0].value = data.stats.totalUsers?.toString() || '0'
                statsData.value[1].value = data.stats.totalCommunities?.toString() || '0'
                statsData.value[2].value = data.stats.totalParkingSpaces?.toString() || '1,256'
                statsData.value[3].value = data.stats.onlineDevicesPercent?.toString() + '%' || '98.5%'
            }
            
            // 更新额外统计数据
            if (data.stats) {
                additionalStatsData.value[0].value = data.stats.totalBuildings?.toString() || '0'
                additionalStatsData.value[1].value = data.stats.totalUnits?.toString() || '0'
                additionalStatsData.value[2].value = data.stats.totalHouseholds?.toString() || '0'
                additionalStatsData.value[3].value = data.stats.totalOwners?.toString() || '0'
            }
            
            // 更新公告列表
            if (data.notices) {
                noticeList.value = data.notices
            }
            
            // 更新图表数据
            if (data.chart) {
                updateChart(data.chart)
            }
        }
    } catch (error) {
        console.error('加载仪表盘数据失败:', error)
    }
}

// 更新图表
const updateChart = (chartData: any) => {
    try {
        if (!chartRef.value || !document.contains(chartRef.value)) {
            console.warn('Dashboard图表DOM元素未准备好，跳过更新')
            return
        }

        const chart = echarts.init(chartRef.value)
        const option = {
            title: {
                text: '月度数据统计',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['用户注册', '物业缴费', '维修申请'],
                bottom: 10
            },
            xAxis: {
                type: 'category',
                data: chartData.xAxis || ['1月', '2月', '3月', '4月', '5月', '6月']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '用户注册',
                    type: 'line',
                    data: chartData.userRegistrations || [0, 0, 0, 0, 0, 0],
                    smooth: true,
                    itemStyle: {
                        color: '#2d8cf0'
                    }
                },
                {
                    name: '物业缴费',
                    type: 'line',
                    data: chartData.propertyFees || [0, 0, 0, 0, 0, 0],
                    smooth: true,
                    itemStyle: {
                        color: '#19be6b'
                    }
                },
                {
                    name: '维修申请',
                    type: 'line',
                    data: chartData.repairApplications || [0, 0, 0, 0, 0, 0],
                    smooth: true,
                    itemStyle: {
                        color: '#ff9900'
                    }
                }
            ]
        }

        chart.setOption(option)

        // 响应式
        const safeResizeHandler = () => {
            try {
                if (chart && !chart.isDisposed()) {
                    chart.resize()
                }
            } catch (error) {
                if (error instanceof Error && 
                    (error.message.includes('getAttribute') || 
                     error.message.includes('getBoundingClientRect'))) {
                    console.warn('Dashboard图表resize操作跳过')
                    return
                }
                throw error
            }
        }
        
        window.addEventListener('resize', safeResizeHandler)
    } catch (error) {
        if (error instanceof Error && 
            (error.message.includes('getAttribute') || 
             error.message.includes('getBoundingClientRect'))) {
            console.warn('Dashboard图表更新失败，DOM元素未准备好')
            return
        }
        throw error
    }
}

// 初始化图表
const initChart = () => {
    try {
        if (!chartRef.value || !document.contains(chartRef.value)) {
            console.warn('Dashboard图表DOM元素未准备好，跳过初始化')
            return
        }

        const chart = echarts.init(chartRef.value)
        const option = {
            title: {
                text: '月度数据统计',
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['用户注册', '物业缴费', '维修申请'],
                bottom: 10
            },
            xAxis: {
                type: 'category',
                data: ['1月', '2月', '3月', '4月', '5月', '6月']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '用户注册',
                    type: 'line',
                    data: [0, 0, 0, 0, 0, 0],
                    smooth: true,
                    itemStyle: {
                        color: '#2d8cf0'
                    }
                },
                {
                    name: '物业缴费',
                    type: 'line',
                    data: [0, 0, 0, 0, 0, 0],
                    smooth: true,
                    itemStyle: {
                        color: '#19be6b'
                    }
                },
                {
                    name: '维修申请',
                    type: 'line',
                    data: [0, 0, 0, 0, 0, 0],
                    smooth: true,
                    itemStyle: {
                        color: '#ff9900'
                    }
                }
            ]
        }

        chart.setOption(option)

        // 响应式
        const safeResizeHandler = () => {
            try {
                if (chart && !chart.isDisposed()) {
                    chart.resize()
                }
            } catch (error) {
                if (error instanceof Error && 
                    (error.message.includes('getAttribute') || 
                     error.message.includes('getBoundingClientRect'))) {
                    console.warn('Dashboard图表resize操作跳过')
                    return
                }
                throw error
            }
        }
        
        window.addEventListener('resize', safeResizeHandler)
    } catch (error) {
        if (error instanceof Error && 
            (error.message.includes('getAttribute') || 
             error.message.includes('getBoundingClientRect'))) {
            console.warn('Dashboard图表初始化失败，DOM元素未准备好')
            return
        }
        throw error
    }
}

// 组件挂载
onMounted(() => {
    nextTick(() => {
        initChart()
        loadDashboardData()
    })
})
</script>

<style scoped lang="scss">
.dashboard {
    padding: 24px;

    .dashboard-header {
        margin-bottom: 32px;
        text-align: center;

        .page-title {
            font-size: 32px;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 8px;
        }

        .page-description {
            font-size: 16px;
            color: var(--text-secondary);
            margin: 0;
        }
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 24px;
        margin-bottom: 32px;

        .stat-card {
            border: none;
            border-radius: 12px;

            .stat-content {
                display: flex;
                align-items: center;

                .stat-icon {
                    width: 64px;
                    height: 64px;
                    border-radius: 12px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 16px;
                }

                .stat-info {
                    flex: 1;

                    .stat-title {
                        font-size: 14px;
                        color: var(--text-secondary);
                        margin-bottom: 4px;
                    }

                    .stat-value {
                        font-size: 24px;
                        font-weight: 600;
                        color: var(--text-primary);
                        margin-bottom: 4px;
                    }

                    .stat-change {
                        font-size: 12px;
                        display: flex;
                        align-items: center;
                        gap: 4px;

                        &.up {
                            color: #19be6b;
                        }

                        &.down {
                            color: #ed4014;
                        }
                    }
                }
            }
        }
    }

    .charts-grid {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: 24px;
        margin-bottom: 32px;

        .chart-card {
            border: none;
            border-radius: 12px;

            .card-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-weight: 500;
            }

            .chart-container {
                height: 300px;
            }

            .notice-list {
                .notice-item {
                    padding: 12px 0;
                    border-bottom: 1px solid var(--border-color);

                    &:last-child {
                        border-bottom: none;
                    }

                    .notice-title {
                        font-size: 14px;
                        color: var(--text-primary);
                        margin-bottom: 4px;
                        cursor: pointer;

                        &:hover {
                            color: var(--primary-color);
                        }
                    }

                    .notice-time {
                        font-size: 12px;
                        color: var(--text-secondary);
                    }
                }

                .empty-notice {
                    padding: 40px 0;
                    text-align: center;
                }
            }
        }
    }

}

@media (max-width: 768px) {
    .dashboard {
        padding: 16px;

        .charts-grid {
            grid-template-columns: 1fr;
        }

        .stats-grid {
            grid-template-columns: 1fr;
        }

        .actions-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }
}
</style>
